<template>
  <div class="p-2">
    <div class="goods_form">
      <!-- 顶部步骤条 star -->
<!--      <div class="step_bar">-->
<!--        <div class="step">-->
<!--          <div :class="{item:true,check:query.step == 1,success:query.step>1}">-->
<!--            <el-icon :size="16">-->
<!--              <List />-->
<!--            </el-icon>-->
<!--            编辑商品-->
<!--          </div>-->
<!--          <div :class="{item:true,check:query.step == 3,success:query.step>3}">-->
<!--            <el-icon :size="16">-->
<!--              <SetUp />-->
<!--            </el-icon>-->
<!--            规格编辑-->
<!--          </div>-->
<!--          <div class="item">-->
<!--            <el-icon :size="16">-->
<!--              <CircleCheckFilled />-->
<!--            </el-icon>-->
<!--            发布商品-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
      <!-- 顶部步骤条 end -->
      <!-- 商品主体 star -->
      <div class="goods_form_item" v-if="query.step == 1">
        <el-form ref="formRef" label-position="right" :model="form" :rules="rules" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="当前类目" prop="cate3Id">
                <el-cascader
                  style="width: 300px;"
                  v-model="form.cate3Id"
                  :options="categoryList"
                  :props="{ children: 'children', label: 'name', value: 'id' }"
                  @change="handleChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品品牌" prop="brandId">
                <el-select v-model="form.brandId" placeholder="请选择品牌id" clearable :disabled="query.isDisabled"
                           style="width: 100%">
                  <el-option v-for="item in brandList" :key="item.id" :label="item.brandName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品标题" prop="name">
                <el-input v-model="form.name" placeholder="请输入商品标题" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="副标题" prop="subName">
                <el-input v-model="form.subName" type="textarea" :rows="2" placeholder="请输入副标题" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="商品图片" prop="imgUrl">
                <image-upload v-model="form.ossId" @update:urls="url" class="custom-upload" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item :label="'平台价格'" prop="price">
                <el-input type="number" v-model="form.price">
                  <template #suffix>￥</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="'市场价格'" prop="oldPrice">
                <el-input type="number" v-model="form.oldPrice">
                  <template #suffix>￥</template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item :label="'商品库存'" prop="goods_stock">
                <el-input type="number" v-model="form.stock" :suffix-icon="PieChart" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品详情" prop="details">
                <editor v-model="form.details.content" :min-height="200" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="'是否上架'" prop="status">
                <el-switch v-model="form.status" :active-value="1" :inactive-value="0" @change="statusChange" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
<!--                <el-button type="primary" @click="nextStep(3)" :disabled="disabled">下一步，填写规格信息</el-button>-->
                <el-button type="primary" @click="handleAdd" :disabled="disabled">下一步，填写规格信息</el-button>
                <el-button :icon="CircleCheck" type="success" :loading="loading" @click="nextStep(2)">发布</el-button>
                <el-button @click="goodsBack">返回</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!--商品主体 end-->

      <div class="goods_form_item" v-if="query.step == 2">
<!--等待1秒钟后关闭el-result组件并跳转到指定的/index页面怎么写？ -->
        <el-result icon="success" title="操作成功" sub-title="等待页面跳转……" />
      </div>
      <!--商品规格 star -->
      <div class="goods_form_item" v-if="query.step == 3">
        <sku-item :goods="form" @step="nextStep" />
      </div>

      <!--商品规格 end -->
    </div>
  </div>
</template>
<script setup lang="ts">

import { CircleCheck, CircleCheckFilled, List, PieChart, Reading, SetUp } from '@element-plus/icons-vue';
import { MallGoodsForm, MallGoodsQuery } from '@/api/mall/mallGoods/types';
import { listGoodsCategory } from '@/api/mall/goodsCategory';
import { listCateBrand } from '@/api/mall/cateBrand';
import { specByGoodsIdListApi } from '@/api/mall/goodsSpec';
import SkuItem from '@/views/mall/mallGoods/components/SkuItem.vue';
import { addMallGoods, updateMallGoods } from '@/api/mall/mallGoods';
const props = defineProps({
  rowData: {
    type: Object,
    default: () => {}
  }
});
const emit = defineEmits(['closeAdd','getList'])
const loading = ref(false);
const formRef = ref<ElFormInstance>();
const disabled = ref(false);
const dialogVisible = ref(false)
const specs = ref([])
const query = reactive({
  step: 1,
  choseId: [0, 0, 0],
  index: [0, 0, 0],
  classList: [],
  choseItem: [{}, {}, {}],
  isDisabled: true
});

const initFormData: MallGoodsForm = {
  id: undefined,
  brandId: undefined,
  cate1Id: undefined,
  cate2Id: undefined,
  cate3Id: undefined,
  name: undefined,
  subName: undefined,
  price: undefined,
  oldPrice: undefined,
  imgUrl: undefined,
  ossId: undefined,
  sale: undefined,
  collect: undefined,
  status: 0,
  verify: undefined,
  refuseInfo: undefined,
  freightId: undefined,
  contentMobile: undefined,
  isRecommend: undefined,
  isMaster: undefined,
  specs: [],
  skus: [{}],
  details: {}
};
const data = reactive<PageData<MallGoodsForm, MallGoodsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    params: {},
    cateId: undefined,
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    cate3Id: [{ required: true, message: '商品分类不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
    price: [{ required: true, message: '销售量不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '上架状态不能为空', trigger: 'change' }],
    details: [{ required: true, message: '详情不能为空', trigger: 'change' }]
  }
});
const { queryParams, form, rules } = toRefs(data);
watch(
  () => props.rowData,
  () => {
    console.log(props.rowData);
    form.value = props.rowData as any;
    queryParams.value.cateId = props.rowData.cateId;
    // 品牌可编辑
    // isDisabled.value = false;
    // 参数
    queryParams.value.cateId = props.rowData.cate3Id;
    //复选框选中状态
    // selectedSpecIds.value = form.value.specValue.map((item) => item.specId);
  }
);
watch(()=>query.step,()=>{
  if(query.step ===2){
//关闭添加，回到列表页
    setTimeout(()=>{
      emit('closeAdd',1)
    },500)
    emit('getList')
  }
})
/*获取分类列表*/
type GoodsCategoryOption = {
  id: number;
  name: string;
  children?: GoodsCategoryOption[];
};
const categoryList = ref<GoodsCategoryOption[]>([]);
const getCategoryData = async () => {
  let res = await listGoodsCategory();
  console.log(res);
  categoryList.value = res.data;
};

/*选择分类后获取对应值*/
const specCateId = ref<number>(null);
const handleChange = (value) => {
  //商品分类第3级
  queryParams.value.cateId = value[2];
  //商品规格参数
  specCateId.value = value[2];
  //商品分类赋值
  form.value.cate1Id = value[0];
  form.value.cate2Id = value[1];
  form.value.cate3Id = value[2];
  //查询商品规格
  // getSPecData();
  //查询商品品牌
  query.isDisabled = false;
  getBrandData();
};
/*获取品牌列表*/
const brandList = ref<any>([]);
const getBrandData = async () => {
  const { rows } = await listCateBrand(queryParams.value);
  console.log(rows);
  brandList.value = rows;
};
/*图片组件回传值*/
const url = (e: []) => {
  form.value.imgUrl = e.join(',');
};

/*添加商品规格界面*/
const addSpec = ()=>{
  dialogVisible.value = true;

}
// 公共返回列表页面
const goodsBack = () => {
  location.reload();
};

/*商品上架*/
const statusChange = (ev) => {
  form.value.status = ev;
};
/*下一步，商品发布*/
const handleAdd=()=>{
  //仅在非编辑状态下执行
  formRef.value.validate(async (valid)=>{
    if(!valid) return false;
    if(form.value.id){
      const res = await updateMallGoods(form.value)
      console.log(res);
      specQueryParams.value.goodsId = res.data.id
    }else{
      const res = await addMallGoods(form.value)
      console.log(res);
      //TODO 页面跳转，带上res.data传过去
      specQueryParams.value.goodsId = res.data
    }
    //页面跳转
    query.step = 3
  })
}
/*获取商品规格*/
const specQueryParams =ref({
  goodsId: ""
})
const getSpecs=async ()=>{
  const res = await specByGoodsIdListApi(specQueryParams.value)
  specs.value = res.data;
  console.log(res);
}
const nextStep = (e) => {
  query.step = e;
  if (e === 2) { //发布
    formRef.value.validate(async (valid)=>{
      //这里结果是false怎么仍然执行了下一下步呢
      if(!valid) return false;
        if(form.value.id){
          await updateMallGoods(form.value)
        }else{
          await addMallGoods(form.value)
        }
      //关闭添加，回到列表页
      setTimeout(()=>{
        emit('closeAdd',1)
      },500)
      emit('getList')
    })
  }
  if (query.step === 1) { //添加商品
    // getSpecs();
    formRef.value?.validate((valid) => {
      console.log(valid);
      if (valid) {
        disabled.value = true
      }
    });
  }
  if (query.step === 3) { //添加sku
    getSpecs();
  }
}
onMounted(() => {

  getCategoryData();
});

</script>
<style scoped lang="scss">
.goods_form{
  padding: 20px 60px;
}
.step {
  height: 46px;
  line-height: 46px;
  background: #F5F7FA;
  margin-bottom: 50px;
  display: flex;

  .item {
    flex: 1;
    font-size: 16px;
    color: #C0C4CC;
    text-align: center;
    border-right: 4px solid #fff;
    justify-content: center;
    align-items: center;
    display: flex;

    i {
      margin-right: 10px;
    }

    &.check {
      color: #333;
      font-weight: bold;
    }

    &.success {
      color: #67C23A;
      font-weight: bold;
    }

    &:last-child {
      margin-right: 0px;
    }
  }
}
</style>
